package com.fsy.spring.annotation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by shuangyu.feng on 2017/8/9.
 */
@Slf4j
@Component
public class TaskHandlerRegister extends ApplicationObjectSupport{

	private static Map<String, AbstractTaskHandler> TASK_HANDLERS_MAP = new HashMap<>();

	@Override
	protected void initApplicationContext(ApplicationContext context) throws BeansException {
		super.initApplicationContext(context);
		Map<String, Object> taskBeanMap = context.getBeansWithAnnotation(TaskHandler.class);
		taskBeanMap.keySet().forEach(beanName -> {
			Object bean = taskBeanMap.get(beanName);
			Class clazz = bean.getClass();
			if (bean instanceof AbstractTaskHandler && clazz.getAnnotation(TaskHandler.class) != null) {
				TaskHandler taskHandler = (TaskHandler) clazz.getAnnotation(TaskHandler.class);
				String taskType = taskHandler.taskType();
				if (TASK_HANDLERS_MAP.keySet().contains(taskType)) {
					throw new RuntimeException("TaskType has Exits. TaskType=" + taskType);
				}
				TASK_HANDLERS_MAP.put(taskHandler.taskType(), (AbstractTaskHandler) taskBeanMap.get(beanName));
				log.info("Task Handler Register. taskType={},beanName={}", taskHandler.taskType(), beanName);
			}
		});
	}

	public static AbstractTaskHandler getTaskHandler(String taskType) {
		return TASK_HANDLERS_MAP.get(taskType);
	}
}
